<?php
// +----------------------------------------------------------------------
// | 杭州十禾信息科技有限公司
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2015 http://www.shelpe.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: LeePuman <ysyzlsm@163.com>
// +----------------------------------------------------------------------

class UserAction extends AccountAction
{
	public function index($value='')
	{
		redirect('user/userList');
	}

	public function userList()
	{
		$page = I('page');
		$page = (int)$page > 0 ? $page : 1;
		$pageSize = 50;
		$size = ($page-1)*$pageSize;

		$order = strtolower(I('order'));
		// $orderStatus = false;
		switch ($order) {
			case 'created_time':
			case 'purchase_expires':
			case 'nick':
				$order = 'u.' . $order;
				break;
			case 'qq':
			case 'tel':
				$order = 'ul.' . $order;
				break;
			case 'status':
				break;
			case 'login_time':
			default:
				$order = 'ulr.login_time';
				break;
		}

		$asc = strtolower(I('asc'));
		$asc = $asc == 'asc' ? 'ASC' : 'DESC';

		$search = I('search');
		$params = '';
		if(isset($search['nick']) && $search['nick']) {
			$nick = trim($search['nick']);
			$this->assign('nick', $nick);
			$params .= " AND u.nick LIKE '%{$nick}%'";
			unset($nick);
		}

		$totalCount = M()->table('users u')->where("u.item_code != '' {$params}")->count();
		$totalPage = ceil($totalCount/$pageSize);
		$users = M()->field("u.user_id,u.nick,ul.tel,ul.qq,u.created_time,u.purchase_expires,MAX(ulr.login_time) login_time,if(u.purchase_expires < NOW(),'已过期',(if(login_time, '已登录', '已订购'))) as `status`")
					->table('users u')
					->join('LEFT JOIN user_login_records ulr ON u.user_id = ulr.user_id AND ulr.login_mode = \'code\'')
					->join('LEFT JOIN user_info ul ON u.user_id = ul.user_id')
					->where("item_code != '' {$params}")
					->group('u.user_id')
					->order($order . ' ' . $asc)
					->limit($size, $pageSize)
					->select();
		if($users) {
			$express = array(
					'source' => SSOSROUCE,
					'_t' => time(),
					'source_login' => 'admin'
				);
			foreach ($users as &$user) {
				$express['nick'] = $user['nick'];
				$encrypted_auth_token = base64_encode(authcode(http_build_query($express), 'ENCODE'));
				$user['href'] = U("/login@simba?encrypted_auth_token={$encrypted_auth_token}");
			}
		}

		$this->assign('users', $users);



		

		$this->assign('currentPage', $page);
		$this->assign('totalPage', $totalPage);
		$this->assign('lastPage', $page <= 1 ? 1 : $page-1);
		$this->assign('nextPage', $page >= $totalPage ? $totalPage : $page+1);

		$query = array();
		if(I('search'))
			$query['search'] = I('search');
		$query['order'] = preg_replace('/[\w]*\./','',$order);
		$query['asc'] = $asc;
		$this->assign('current_search', $query ? ('&' . http_build_query($query)) : '');
		$this->assign('order', $query['order']);
		$this->assign('asc', $query['asc']);

		$this->display();
	}

	public function userProfitList($value='')
	{
		$page = I('page');
		$page = (int)$page > 0 ? $page : 1;
		$pageSize = 50;
		$size = ($page-1)*$pageSize;
		
		$order = I('order');
		// $order = $order ? $order : 'u.created_time';
		switch ($order) {
			case 'like_pay':
			case 'like_cost':
			case 'like_roi':
			case 'nick':
			case 'click':
			case 'cpc':
			case 'ctr':
			case 'cost':
			case 'sales':
			case 'balance':
				break;
			default:
				$order = 'balance';
				break;
		}

		$asc = strtolower(I('asc'));
		$asc = $asc == 'asc' ? 'asc' : 'desc';

		$where = I('search');
		$params = '';
		if(isset($where['from']) && $where['from']) {
			$from = trim($where['from']);
			unset($where['from']);
		} else {
			$from = date('Y-m-d', strtotime('-7 day'));
		}

		if(isset($where['to']) && $where['to']) {
			$to = trim($where['to']);
			unset($where['to']);
		} else {
			$to = date('Y-m-d', strtotime('-1 day'));
		}
		$dateTime = " AND rpt.date BETWEEN '{$from}' AND '{$to}'";
		if($where) {
			
			foreach ($where as $key => $value) {
				if($key == 'nick' && $value) {
					$value = trim($value);
					$params .= " AND u.{$key} LIKE '%{$value}%'";
					continue;
				}
			}
		}

		$totalCount = M()->table('users u')->where("u.item_code != '' {$params}")->count();
		$totalPage = ceil($totalCount/$pageSize);
		$users = M()->field('u.user_id,u.nick,0 like_pay,0 like_cost,0 like_roi,SUM(rpt.click) click,(SUM(rpt.cost)/SUM(click))/100 cpc,FORMAT(SUM(click)/SUM(impressions) * 100, 2) ctr,SUM(direct_pay_count + indirect_pay_count)/SUM(click) * 100 cvr,SUM(rpt.cost)/100 cost,SUM(direct_pay + indirect_pay)/100 sales,SUM(direct_pay + indirect_pay)/SUM(cost) roi,u.balance')
					->table('users u')
					->join("LEFT JOIN rpt_customer rpt ON u.user_id = rpt.taobao_user_id {$dateTime}")
					->where("u.item_code != '' {$params}")
					->group('u.user_id')
					// ->order($order . ' ' .($asc == 'desc' ? 'DESC' : 'ASC'))
					// ->limit($size, $pageSize)
					->select();
		if($users) {
			
			foreach ($users as $key => $user) {
				$users[$user['user_id']] = $user;
				unset($users[$key]);
			}


			$user_iids = array_column($users, 'user_id');
			$sql = "SELECT
						cam.user_id,
						sum(rpt.cost)/100 like_cost,
						(sum(rpt.direct_pay) + sum(rpt.indirect_pay))/100 like_pay,
						FORMAT((sum(rpt.direct_pay) + sum(rpt.indirect_pay)) / sum(rpt.cost),2) like_roi
					FROM
						`rpt_campaign` rpt,
						campaigns cam
					LEFT JOIN users u ON u.user_id = cam.user_id AND u.item_code != ''
					WHERE
						rpt.campaign_id = cam.campaign_id
					AND cam.title LIKE '%云智投%'
					{$dateTime}
					AND cam.user_id in(".implode(',', $user_iids).")
					GROUP BY cam.user_id";
			$res = M()->query($sql);
			if($res) {
				$user_iids_rpt_like = array_column($res, 'user_id');
				foreach ($res as $key => $user) {
					$res[$user['user_id']] = $user;
					unset($res[$key]);
				}

				foreach ($user_iids_rpt_like as $user_id) {
					if(in_array($user_id, $user_iids)) {
						$users[$user_id] = array_merge($users[$user_id], $res[$user_id]);
					}
				}
			}
		}


		
		if($order)  {
			$func = "uc_cmp_userProfitList_{$order}_{$asc}";
			usort($users, $func);
		}

		$users = array_slice($users, $size, $pageSize);

		$query = array();
		if(I('search'))
			$query['search'] = I('search');
		$query['order'] = $order;
		$query['asc'] = $asc;
		
		$this->assign('users', $users);
		
		$this->assign('totalPage', $totalPage);
		$this->assign('lastPage', $page <= 1 ? 1 : $page-1);
		$this->assign('currentPage', $page);
		$this->assign('nextPage', $page >= $totalPage ? $totalPage : $page+1);
		$this->assign('current_search', $query ? ('&' . http_build_query($query)) : '');
		$this->assign('dateTime', array('from'=> $from, 'to'=> $to));

		$this->assign('order', $order);
		$this->assign('asc', strtoupper($asc));

		$this->display();
	}

	public function ajaxGetUserTotalData()
	{
		$code = RetStatus::OK;
		try {
			// if(!$this->isAjax())
			// 	throw new Exception("method error", RetStatus::INTER_ERR);
			$search = I('search');
			if(!isset($search['from']) || !isset($search['to']) || !$search['from'] || !$search['to']) {
				throw new Exception("please enter time range", RetStatus::INTER_ERR);
			}
			$from = $search['from'];
			$to = $search['to'];
			$dateTime = " AND rpt.date BETWEEN '{$from}' AND '{$to}'";
			$res = M()->field('FORMAT((SUM(rpt.cost)/SUM(click))/100, 2) cpc,FORMAT(SUM(click)/SUM(impressions) * 100, 2) ctr,FORMAT(SUM(rpt.cost)/100, 2) cost,FORMAT(SUM(direct_pay + indirect_pay)/100, 2) sales,FORMAT(SUM(direct_pay + indirect_pay)/SUM(cost), 2) roi')
					->table('users u')
					->join("LEFT JOIN rpt_customer rpt ON u.user_id = rpt.taobao_user_id {$dateTime}")
					->where("u.item_code != ''")
					->find();
			$res['totalCount'] = M()->table('users')->where("item_code != ''")->count();

			$tmp = M()->field('FORMAT(sum(rpt.cost)/100, 2) like_cost,FORMAT((sum(rpt.direct_pay) + sum(rpt.indirect_pay))/100, 2) like_pay,FORMAT((sum(rpt.direct_pay) + sum(rpt.indirect_pay)) / sum(rpt.cost), 2) like_roi')
					->table('rpt_campaign rpt,campaigns cam')
					->join("LEFT JOIN users u ON u.user_id = cam.user_id")
					->where("u.item_code != '' AND rpt.campaign_id = cam.campaign_id AND cam.title LIKE '%云智投%' {$dateTime}")
					->find();
			$res = array_merge($tmp, $res);
		} catch (Exception $e) {
			$code = $e->getCode();
			$res = array(
					'msg' => $e->getMessage()
				);
		}
		$this->display_json($res, $code);
	}
}